package foo;

import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class EffectiveJava {

	public class HigherLevelException extends RuntimeException {
		public HigherLevelException(final Throwable cause) {
			super(cause);
		}
	}

	public static EffectiveJava staticFactory() {
		return new EffectiveJava();
	}

	protected void aFinalMethod(final String message) {
		System.out.println("Final:" + message);
	}

	protected void testExceptions() {
		throw new HigherLevelException(new RuntimeException("Not working"));
	}

	public void submitWork(final Callable<String> task) throws InterruptedException, ExecutionException {
		try {
			final Future<String> future = Executors.newSingleThreadExecutor().submit(task);
			final String result = future.get();
			System.out.println("State:" + result);
		} catch (final Exception e) {
			System.out.println("Exception:" + e);
		}
	}

	public void submitRunnableWork(final Runnable task) {
		try {
			Executors.newSingleThreadExecutor().execute(task);
		} catch (final Exception e) {
			System.out.println("Exception:" + e);
		}
	}

	public void useLock() {
		final Semaphore s = new Semaphore(5);
	}

	private static volatile boolean stopRequested = false;

	public static void main(final String[] args) throws InterruptedException {
		final Thread t = new Thread(new Runnable() {
			private int i;

			public void run() {
				while (!stopRequested) {
					i++;
					// System.out.println(i);
				}
			}
		});

		t.start();

		TimeUnit.SECONDS.sleep(1);

		stopRequested = true;

		Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

			public void uncaughtException(final Thread t, final Throwable e) {
				// TODO Auto-generated method stub

			}
		});
	}
}
